// pages/cart/index.ts
import {
  showToast,
  login,
  requestPayment
} from "../../utils/asyncWx.js";
import {
  request
} from '../../request/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0,
    checkedCart: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow() {
    let address = wx.getStorageSync('address')
    // 1.获取缓存中的购物车数据
    let cart = wx.getStorageSync("cart") || []
    cart = cart.filter(s => s.checked)
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      totalPrice += v.num * v.goods_price;
      totalNum += v.num;
    })
    // 2.给data赋值
    this.setData({
      checkedCart: cart,
      totalPrice,
      address,
      totalNum
    })
  },

  onLoad() {
    // const cart = wx.getStorageSync("cart") || []
    // // 3.给data赋值
    // this.setData({
    //   cart,
    // })
  },
  async onSubmitPay() {
    try {
      const token = wx.getStorageSync('token')
      if (token) {
        // 创建订单
        // const header = {
        //   Authorization: token
        // }
        let address = this.data.address.provinceName + this.data.address.cityName + this.data.address.countyName +
          this.data.address.detailInfo
        let order_price = this.data.totalPrice
        let consignee_addr = address
        let goods = []
        this.data.checkedCart.forEach(item => {
          goods.push({
            goods_id: item.goods_id,
            goods_number: item.num,
            goods_price: item.goods_price
          })
        })
        let orderParams = {
          order_price,
          consignee_addr,
          goods
        }
        // 获取订单编号
        const {
          order_number
        } = await request({
          url: "my/orders/create",
          method: "post",
          data: orderParams,
        })
        // 发起预支付接口
        const {
          pay
        } = await request({
          url: "my/orders/req_unifiedorder",
          method: "post",
          data: {
            order_number
          },
        })
        // 发起微信支付
        await requestPayment(pay)
        // 查询 后台查看订单支付 状态
        const res = await request({
          url: "my/orders/chkOrder",
          method: "post",
          data: {
            order_number
          },
          header
        })
        // 后台返回 支付成功
        // console.log(res);
        await showToast('支付成功')
        // 再支付完成之后，清除购物车的商品
        let newCarts = wx.getStorageSync('cart')
        newCarts = newCarts.filter(s => !s.checked)
        wx.setStorageSync('cart', newCarts)
        // 支付成功后跳转订单页面
        wx.navigateTo({
          url: '/pages/order/index',
        })
      } else {
        wx.getUserProfile({
          desc: 'desc',
          success: async res => {
            const {
              encryptedData,
              rawData,
              iv,
              signature
            } = res
            const {
              code
            } = await login()
            const loginParams = {
              encryptedData,
              rawData,
              iv,
              signature,
              code
            }
            // 发请求获取token
            const req = await request({
              url: "users/wxlogin",
              data: loginParams,
              method: "post"
            })
            console.log(req);
          },
          fail: rej => {
            console.log("获取权限失败");
          }
        })
      }
    } catch (error) {
      await showToast("支付失败")
      console.log(error)
    }
  }
})